#include <iostream>
#include <unistd.h>
#include <cstring>
#include <cerrno>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string>

const int size = 1024;

std::string GetOtherMessage()
{
    static int cnt = 0;//消息编号
    std::string id = std::to_string(cnt++);//将消息编号转为字符串
    pid_t self_id = getpid();//获取当前进程的pid
    std::string prs_id = std::to_string(self_id);

    //将消息编号、pid拼接在一起
    std::string message = "msg_id: " + id + "  my pid: " + prs_id;
    return message;
}

// 子进程写入
void ChildProcessWrite(int wfd)
{
    std::string msg = "father, i am your child....";
    while (1)
    {
        std::string info = msg + GetOtherMessage();
        write(wfd, info.c_str(), info.size());
        //sleep(1);
    }
}

// 父进程读取
void FatherProcessRead(int rfd)
{
    char buffer[size];
    while (1)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer) -1);
        if(n > 0)
        {
            buffer[n] = '\0';
            std::cout << "Son, i get: " << buffer << std::endl;
            //sleep(1);
        }
        else if(n < 0)
        {
            std::cerr << "read error" << std::endl;
            break;
        }
        else
        {
            std::cerr << "Writer haved quit..., return val is: " << n << std::endl;
            break;
        }
    }
}

int main()
{
    // 创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    // 检查是否创建成功
    if (n != 0)
    {
        std::cerr << "errno: " << errno << "errmsg: " << strerror(errno) << std::endl;
        return -1; // 管道创建失败
    }

    // 创建子进程
    pid_t id = fork();
    // child -> write
    if (id == 0)
    {
        std::cout << "我是子进程, 正在关闭不需要的fd, 要准备发消息了..." << std::endl;
        close(pipefd[0]);             // 关闭不需要的读端
        ChildProcessWrite(pipefd[1]); // 子进程写入
        close(pipefd[1]);             // 通信完毕,关闭写端
        exit(0);
    }

    // father -> read
    std::cout << "我是父进程, 正在关闭不需要的fd, 要准备接收消息了~~~" << std::endl;
    close(pipefd[1]);             // 关闭写端
    sleep(10);
    FatherProcessRead(pipefd[0]); // 父进程读取
    close(pipefd[0]);             // 通信完毕,关闭读端

    // 等待子进程退出
    int status = 0;                      // 获取子进程的退出信息
    pid_t rid = waitpid(id, &status, 0); // 阻塞等待子进程退出
    if (rid > 0)
    {
        std::cout << "wait success" << std::endl;
        std::cout << "quit sig is: " << (status & 0x7f) << std::endl;
        std::cout << "quit code is: " << ((status >> 8) & 0xff) << std::endl;
    }

    std::cout << "father quit..." << std::endl;

    return 0;
}